import re
from rest_framework import serializers
from celery_tasks.emails.tasks import send_email_verify
from users.utils import generate_save_user_token_url
from .models import User, Address
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings


class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='是否同意协议', write_only=True)
    # 增加字段
    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token']
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '用户名在5-20位之间',
                    'max_length': '用户名在5-20位之间'
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '用户名在8-20位之间',
                    'max_length': '用户名在8-20位之间'
                }

            }
        }

    def validate_mobile(self, mobile):
        """验证手机号"""
        if re.match(r'^1[3-9]\d{9}]', mobile):
            raise serializers.ValidationError('手机号错误！')
        count = User.objects.filter(mobile=mobile).count()
        if count > 0:
            raise serializers.ValidationError('手机号已被注册！')
        return mobile

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意协议！')
        return value

    def validate(self, attrs):
        """
        校验密码是否一致
        校验验证码
        """
        # 校验密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        sms_code = attrs.get('sms_code')
        # 判断短信验证码是否正确
        # 把用户提交的短信验证码和redis中保存的判断是否一致
        if password != password2:
            raise serializers.ValidationError('两次输入密码不一致')

        redis = get_redis_connection('verify_codes')
        mobile = attrs.get('mobile')
        # 获取真实的短信验证码
        real_sms_code = redis.get('sms_%s' % mobile)
        # 从redis获取到用户输入的是bytes字节，需要解码,可以是空
        try:
            real_sms_code = real_sms_code.decode()
        except Exception as e:
            raise serializers.ValidationError('短信验证码不存在或已过期')
        if sms_code != real_sms_code:
            raise serializers.ValidationError('验证码输入有误')
        return attrs

    def create(self, validated_data):
        """
        创建用户
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['sms_code']
        del validated_data['password2']
        del validated_data['allow']
        # 调用父类的方法创建用户对象
        user = super().create(validated_data)
        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详情序列化器"""

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmailSerializer(serializers.ModelSerializer):
    """用户邮箱的序列化器"""

    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'required': True
        }

    def update(self, instance, validated_data):
        instance.email = validated_data['email']
        instance.save()
        email = instance.email
        # 生成验证邮箱的链接[instance 就是当前已经登陆的用户]
        # 设定一个公共方法,得到一个邮箱验证地址
        verify_url = generate_save_user_token_url(instance)
        # 使用异步发送邮件
        send_email_verify.delay(email, verify_url)

        # 返回当前用户
        return instance


class UserAddressSerializer(serializers.ModelSerializer):
    """
        用户地址序列化器
        """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_date', 'update_date')

    def validated_mobile(self, value):
        """校验手机"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            return serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """保存数据"""
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)
